package homework.xuluoxi;

/*
 * 作业名称：TCP模型
 * 作业功能：实现客户端与服务器之间的模拟登录
 * 分　　类：服务器
 * 学　　员：徐罗希
 * 版　　本：V1.0
 * 备　　注：模块四作业
 */

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    // 定义私有成员变量
    private ServerSocket serverSocket = null;
    private Socket socket = null;

    public static void main(String[] args) {

        // 等待客户端连接
        Server myServer = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            myServer = new Server();
            myServer.serverSocket = new ServerSocket(3333);
            System.out.println("等待客户端连接中...");
            myServer.socket = myServer.serverSocket.accept();
            System.out.println("客户端连接成功");

            // 接收客户端发送的数据
            ois = new ObjectInputStream(myServer.socket.getInputStream());
            UserMessage userMessage = (UserMessage)ois.readObject();
            System.out.println("客户端传送数据接收成功");

            // 判断数据是否正确
            if ("admin".equals(userMessage.getUser().getUserName()) && "123456".equals(userMessage.getUser().getPassWord())) {
                userMessage.setType("Success");
            }
            else {
                userMessage.setType("Failure");
            }

            // 将结果返回客户端
            oos = new ObjectOutputStream(myServer.socket.getOutputStream());
            oos.writeObject(userMessage);
            System.out.println("结果回传客户端成功");
        }
        catch (IOException |ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            try {
                oos.close();
                ois.close();
                myServer.socket.close();
                myServer.serverSocket.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
